package com.zkq.graduate.interceptor;

import com.alibaba.fastjson.JSON;
import com.zkq.graduate.enums.DateTimeFormatterEnum;
import com.zkq.graduate.util.LocalDateTimeUtil;
import com.zkq.graduate.util.PhotoCaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author zhangkaiqiang
 * @Date 2019/9/30  14:47
 * @Description 阿里短信验证码发送拦截器,控制两次发送短信的间隔时间
 */
@Component
public class SendMessageInterceptor implements HandlerInterceptor {


	@Autowired
	RedisTemplate redisTemplate;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-type", "application/json;charset=UTF-8");
		Map<String,Object> resultMap=new HashMap<>();

		// 腾讯图片验证码返回的票据和加密字符串,校验图片验证码是否正确,正确才进行短信验证码的发送
		String ticket=request.getParameter("ticket");
		String randStr=request.getParameter("randstr");
		String ipAddress=request.getParameter("userIP");
		Map<String,Object> checkResult=PhotoCaptchaUtil.checkPhotoCaptcha(ticket,randStr,ipAddress);

		// 图片验证码通过
		if(Objects.equals(checkResult.get("msg"),"OK")){
			String phone=request.getParameter("phone");
			// 判断该用户是否第一次发送
			String oldSendTime= (String) redisTemplate.opsForHash().get(phone,"sendTime");
			if(oldSendTime==null){
				return true;
			}
			// 判断两次发送验证码的时间间隔是否大于60秒
			if(oldSendTime!=null&& LocalDateTimeUtil.getBetweenTimeWithString(LocalDateTimeUtil.formatLocalDateTime(LocalDateTime.now(), DateTimeFormatterEnum.DEFAULT),oldSendTime)>60){
				return true;
			}
			// 这里设置返回的http status,告诉前端短信验证码请求被拦截
			resultMap.put("code",401);
			resultMap.put("message","指定时间内超出限制的发送次数");
			response.getWriter().print(JSON.toJSONString(resultMap));
			return false;
		}else{
			// 设置返回的http status,告诉前端图片验证码错误
			resultMap.put("code",402);
			resultMap.put("message","图片验证码错误");
			response.getWriter().print(JSON.toJSONString(resultMap));
			return false;
		}




	}

}
